#!/usr/bin/env python
# coding=utf8

from contextlib import contextmanager

from flask.ext.sqlalchemy import SQLAlchemy

from main import app
db = SQLAlchemy(app)

@contextmanager
def session_scope():
    session = db.session()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()

#ORM基本操作
class ORMBase(object):

    def save(self, commit=True, refresh=False):
        with session_scope() as session:
            pre_session = session.object_session(self)
            if pre_session and pre_session != session:
                pre_session.close()
            session.add(self)
            if commit:
                session.commit()
                ret = self.id
            if refresh:
                session.refresh(self)
        return ret

    def update(self, **kwargs):
        with session_scope() as session:
            pre_session = session.object_session(self)
            if pre_session and pre_session != session:
                pre_session.close()
            session.add(self)
            for k in kwargs:
                setattr(self, k, kwargs[k])
            session.commit()
        return self.id

    @classmethod
    def get(cls, type='origin', **filter_kwargs):
        """
        为保证效率，需要保证筛选条件里面至少有一个字段能利用到索引
        如果有多条记录，只返回第一条
        :type: origin, dict, json
        """
        with session_scope() as session:
            model = session.query(cls).filter_by(**filter_kwargs).first()
        if not model:
            return None
        if type == 'dict':
            return model.to_dict()
        elif type == 'json':
            return json.dumps(model.to_dict())
        else:
            return model

    @classmethod
    def get_list(cls, type='origin', **filter_kwargs):
        '''
        为保证效率，需要保证筛选条件里面至少有一个字段能利用到索引
        :type: origin, dict, json
        '''
        with session_scope() as session:
            model_list = session.query(cls).filter_by(**filter_kwargs).all()
        record_list = []
        if type == 'dict':
            for m in model_list:
                record_list.append(m.convert_all(mode='R').to_dict())
            return record_list
        elif type == 'json':
            for m in model_list:
                record_list.append(m.convert_all(mode='R').to_dict())
            return json.dumps(record_list)
        else:
            for m in model_list:
                record_list.append(m.convert_all(mode='R'))
            return record_list

    def convert_all(mode='R'):
        pass

    def to_dict(self):
        raise NotImplementedError
